<template>
  <div class="upload_image_box" :class="size ? 'upload_' + size : ''">
    <!-- <el-upload :action="COMMONFILEUPLOAD" :disabled="disabled" v-if="!pics || pics.length <= 0 || pics.length < Number(limit)" list-type="picture-card" :show-file-list="false" :limit="Number(limit)" :headers="uploadHeaders" :accept="accept" :before-upload="beforeUpload" :on-success="onSuccess">
      <template>
        <i class="el-icon-plus" v-if="!$slots.inner" />
        <slot name="inner" />
      </template>
      <div slot="tip" class="upload_tip" v-if="tip">{{ tip }}</div>
    </el-upload> -->
    <div class="upload_button" @click="openDialog()" v-if="!pics || pics.length <= 0 || pics.length < Number(limit)">
      <i class="el-icon-plus" />
    </div>

    <div class="image_list">
      <cropper-image
        v-for="(item, index) in pics"
        :key="index"
        :info="item"
        @delete="removeImage"
      ></cropper-image>
    </div>

    <!-- 图片裁剪 弹框 开始 -->
    <glsx-dialog :show="showDialog" width="60%" title="上传图片" @close="closeDialog()">
      <div>
        <div class="cropper_tips">
          <p>图片格式只支持：JPEG、JPG、PNG,大小不超过5M</p>
          <p>图片上传后自动按照{{fixedNumber.toString()}}比例进行裁剪</p>
        </div>
        <div class="cropper_btn_box">
          <el-upload
            ref="elUploadBox"
            :action="COMMONFILEUPLOAD"
            :limit="Number(limit)"
            :show-file-list="false"
            :accept="accept"
            :auto-upload="false"
            :on-change="onChange"
          >
            <el-button size="small" type="primary">选择图片</el-button>
          </el-upload>
          <el-button
            type="default"
            size="small"
            class="clear_btn"
            @click="clearImage()"
            >清除</el-button
          >
        </div>
        <div class="cropper_wrapper">
          <div class="cropper_box">
          <vueCropper
            class=""
            ref="cropperImage"
            :img="cropperFile"
            :outputSize="outputSize"
            autoCrop
            fixed
            :fixedNumber="fixedNumber"
            infoTrue
            :autoCropWidth="150"
            @realTime="onRealTime"
          ></vueCropper>
        </div>
          <div class="cropper_preview">
            <div class="preview_title">图片预览</div>
            <div :style="previewsStyles">
              <div :style="previewsInfo.div">
                <img :src="previewsInfo.url" :style="previewsInfo.img" />
              </div>
            </div>
          </div>
        </div>
      </div>
      <div slot="footer">
        <el-button type="primary" size="small" :loading="loading" @click="saveInfo(true)"
          >保存</el-button
        >
        <el-button type="default" size="small" :loading="loading" @click="saveInfo()">保存并继续上传</el-button>
      </div>
    </glsx-dialog>
    <!-- 图片裁剪 弹框 end -->
  </div>
</template>
<script>
import { deepClone } from "@/common/util";
import * as imageConversion from "image-conversion";
import { BASEURL, COMMONFILEUPLOAD } from "@/http/system";
import { COMPRESS_RATE } from "@/common/constants";
import { VueCropper } from "vue-cropper";
import CropperImage from "./image.vue";
import axios from "@/http/api";
export default {
  name: "CropperUpload",
  components: {
    VueCropper,
    CropperImage,
  },
  props: {
    limit: {
      type: [Number, String],
      default: 1,
    },
    value: {
      type: Array,
      default: function () {
        return [];
      },
    },
    disabled: {
      type: Boolean,
      default: false,
    },
    size: {
      type: String,
      default: "", // small  large
    },
    tip: {
      type: [String, Number],
      default: "",
    },
    accept: {
      type: String,
      default: ".jpg,.png,.jpeg",
    },
    fixedNumber: {
      type: Array,
      default: function () {
        return [1, 1];
      },
    },
  },
  data() {
    return {
      pics: [],
      uploadHeaders: {},
      imageList: [],
      COMMONFILEUPLOAD,
      showDialog: false,
      option: {},
      cropperFile: "",
      previewsInfo: {},
      previewsStyles: {},
      outputSize:0.8,
      loading:false
    };
  },
  watch: {
    value: {
      handler: function (n, o) {
        let arr = [];
        if (n && n.length > 0) {
          n.map((k) => {
            let _type = typeof k;
            console.log(_type);
            if (_type == "string") {
              arr.push({
                name: k,
                path: k,
                url: BASEURL + k,
              });
            } else {
              arr.push(k);
            }
          });
        }

        this.pics = arr || [];
      },
      immediate: true,
    },
  },
  created() {
    let token = sessionStorage.getItem("token");
    this.uploadHeaders = { Authorization: token };
  },
  methods: {
    /** 监听文件上传成功 */
    onSuccess(response, isClose) {
      if (response.code == 200) {
        let list = deepClone(this.value || []);
        list.push(response.data);
        this.$emit("input", list);
        this.$emit("change", list);
        this.clearImage()
        if(isClose){
          this.closeDialog()
        }
      }
    },

    // 删除图片
    removeImage(row) {
      console.log(row)
      let arr = [];
      let list = deepClone(this.pics);
      this.imageList = [];
      let _nlist = list.filter((k) => k.path != row.path);
      _nlist.map((k) => {
        arr.push(k.path);
      });
      console.log(arr);
      this.pics = _nlist
      this.$emit("input", arr);
    },

    // 监听文件选择
    onChange(file) {
      console.log(file);
      let _this = this;
      let _file = new FileReader();
      _file.readAsDataURL(file.raw);
      _file.onload = function (e) {
        _this.cropperFile = e.target.result;
      };
    },

    // 打开裁剪弹框
    openDialog() {
      this.showDialog = true;
    },

    // 关闭弹框
    closeDialog(){
      this.showDialog = false;
    },

    // 实时监听裁剪框
    onRealTime(data) {
      console.log(data);
      this.previewsStyles = {
        width: data.w + "px",
        height: data.h + "px",
        overflow: "hidden",
        margin: "0",
        zoom: 0.8,
      };
      this.previewsInfo = data;
    },

    // 清空选择
    clearImage() {
      this.$refs.elUploadBox.clearFiles();
      this.previewsInfo = {};
      this.previewsStyles = {};
      this.cropperFile = "";
      this.$refs.cropperImage.clearCrop();
    },

    // blob转base64
    blobToFile(theBlob, fileName) {
      let _arr = theBlob.type.split('/');
      let _name = fileName || new Date().getTime() + "." +_arr[_arr.length-1];
      theBlob.lastModifiedDate = new Date(); // 文件最后的修改日期
      theBlob.name = _name; // 文件名
      let _file = new File([theBlob], _name, {
        type: theBlob.type,
        lastModified: Date.now(),
      });
      return _file;
    },

    // 图片上传
    saveInfo(isClose) {
      let _this = this;
      this.$refs.cropperImage.getCropBlob((data) => {
        console.log(data);
        let _file = _this.blobToFile(data);
        _this.uploadImageToServer(_file,isClose);
      });
    },

    // 上传图片
    async uploadImageToServer(file,isClose) {
      let headers = { "Content-Type": "multipart/form-data" };
      let o = new FormData();
      o.append("file", file);
      //headers.Authorization = sessionStorage.getItem("token");
      console.log(file);
      this.loading = true;
      let res = await axios({
        method: "post",
        withCredentials: false,
        url: COMMONFILEUPLOAD,
        data: o,
        headers: headers,
      });
      this.loading = false;
      this.onSuccess(res,isClose)
    },
  },
};
</script>
<style lang="scss" scoped>
.upload_button {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 148px;
  height: 148px;
  border: 1px dashed #c0ccda;
  border-radius: 6px;
  box-sizing: border-box;
  background: #fbfdff;
  cursor: pointer;
  i {
    font-size: 28px;
    color: #8c939d;
  }
}
.upload_button:hover {
  border-color: #409eff;
  color: #409eff;
}
.upload_image_box {
  display: flex;

  .upload_tip {
    color: #999;
    font-size: 12px;
  }

  .image_list {
    display: flex;
    flex-wrap: wrap;
    margin-left: 10px;
  }
}

.upload_small {
  ::v-deep .el-upload {
    width: 100px;
    height: 100px;
    line-height: 100px;
  }

  ::v-deep .image_list {
    .image_cell {
      width: 100px;
      height: 100px;
    }
  }
}
.cropper_box {
  width: 500px;
  height: 300px;
}
.cropper_wrapper {
  display: flex;
  margin-top: 10px;
  .cropper_preview {
    margin-left: 10px;
    .preview_title {
      line-height: 1;
      margin-bottom: 10px;
    }
  }
}
.cropper_btn_box {
  display: flex;
  align-items: center;
  .clear_btn {
    margin-left: 10px;
  }
}
</style>